// 等待
function WaitingCtrl() {
    // 当前执行的ajax请求的数量
    this.count = 0;
    // 显示等待
    this.show = function () {
        if (this.count === 0) {
            $(".waiting").show();
        }
        this.count = this.count + 1;
    };
    // 隐藏等待
    this.complete = function () {
        this.count = this.count - 1;
        if (this.count === 0) {
            $(".waiting").hide();
        }
    };
}
// 确认
function ConfirmCtrl() {
    // 显示等待
    this.show = function (content, callback, cancel, sure) {
        $("#confirm .modal-body").html(content);
        $("#confirm-sure").unbind("click").bind("click", function () {
            $("#confirm").modal('hide');
            callback();
        });
        if (Utils.notEmpty(cancel)) {
            $("#confirm-cancel").html(cancel);
        } else {
            $("#confirm-cancel").html("取消");
        }
        if (Utils.notEmpty(sure)) {
            $("#confirm-sure").html(sure);
        } else {
            $("#confirm-sure").html("确认");
        }
        $("#confirm").modal('show');
    };
    // 隐藏等待
    this.hide = function () {
        $("#confirm").modal('hide');
    };
}
// 用户认证
function AuthCtrl() {
    // 当前登录用户
    this.session = undefined;
    // 获取到当前用户的事件监听器
    this.sessionListener = [];
    // 执行登录
    this.login = function (username, password) {
        $.ajax({
            url: Url.baseService.login,
            type: HttpMethod.post,
            data: {username: username, password: password},
            success: function (result, status, xhr) {
                window.location.href = Url.ui.iframe;
            }
        })
    };
    // 执行登出
    this.logout = function () {
        $.ajax({
            url: Url.baseService.logout,
            type: HttpMethod.post,
            success: function (result, status, xhr) {
                window.location.href = Url.ui.login;
            }
        })
    };
    // 获取当前用户
    this.getSession = function () {
        var self = this;
        $.ajax({
            url: Url.baseService.session,
            type: HttpMethod.get,
            async: false,
            success: function (result, status, xhr) {
                self.session = result;
                var error = [];
                for (var i = 0; i < self.sessionListener.length; i++) {
                    try {
                        self.sessionListener[i](self.session);
                    } catch (e) {
                        console.warn(e);
                        error.push(i);
                    }
                }
                for (var i = 0; i < error.length; i++) {
                    self.sessionListener.splice(error[i], 1);
                }
            }
        });
    };
    // 讲当前用户信息显示到页面上
    this.setSession = function () {
        $("#curr-user-name").html(this.session.userName);
        $("#curr-user-image").attr("src", Utils.getHeadImageForFrame(this.session.image));
    };
    // 发送http心跳
    this.heartbeat = function () {
        $.ajax({
            url: Url.baseService.heartbeat,
            type: HttpMethod.get
        });
    };
}
// 用户管理
function UserCtrl() {
    // 当前系统所有用户
    this.users = [];
    // 获取到当前系统所有用户的监听器
    this.userListener = [];
    // 获取当前系统所有用户
    this.getUsers = function () {
        var self = this;
        $.ajax({
            url: Url.baseService.userPage,
            type: HttpMethod.get,
            headers: {pageSize: MaxPageSize, pageNumber: 1},
            success: function (result, status, xhr) {
                self.users = result.records;
                var error = [];
                for (var i = 0; i < self.userListener.length; i++) {
                    try {
                        self.userListener[i](self.users);
                    } catch (e) {
                        console.warn(e);
                        error.push(i);
                    }
                }
                for (var i = 0; i < error.length; i++) {
                    self.userListener.splice(error[i], 1);
                }
            }
        });
    };
    // 根据用户id查询用户
    this.getUser = function (userId) {
        for (var i = 0; i < this.users.length; i++) {
            if (userId === this.users[i].id) {
                return this.users[i];
            }
        }
        return undefined;
    };
    // 用户上线
    this.userOnline = function (userId) {
        var user = this.getUser(userId);
        if (user) {
            user.online = true;
        }
    };
    // 用户下线
    this.userOffline = function (userId) {
        var user = this.getUser(userId);
        if (user) {
            user.online = false;
        }
    };
}
// WebSocket
function WebsocketCtrl() {
    // 当前websocket连接
    this.websocket = undefined;
    // 获取到消息的事件监听器
    this.noticeListener = [];
    // 获取到站内信的事件监听器
    this.letterListener = [];
    // 获取到任务的事件监听器
    this.taskListener = [];
    // 获取到及时聊天的事件监听器
    this.chatListener = [];
    // 获取到系统事件的事件监听器
    this.eventListener = [];
    // 验证当前websocket连接是否可用
    this.validate = function () {
        return this.websocket.readyState === WebSocket.CONNECTING || this.websocket.readyState === WebSocket.OPEN;
    };
    // 连接到websocket服务端
    this.connect = function (userId) {
        var self = this;
        console.log("websocket connecting");
        this.websocket = new WebSocket("ws://" + window.location.host + Url.websocket + "?userId=" + userId);
        this.websocket.onopen = function (ev) {
            console.log("websocket connected: " + ev);
        };
        this.websocket.onmessage = function (ev) {
            if (Utils.notEmpty(ev.data)) {
                console.log("websocker message: " + ev.data);
                var message = JSON.parse(ev.data);
                if (message.type === "NOTICE") {
                    var notice = message.message;
                    var error = [];
                    for (var i = 0; i < self.noticeListener.length; i++) {
                        try {
                            self.noticeListener[i](notice);
                        } catch (e) {
                            console.warn(e);
                            error.push(i);
                        }
                    }
                    for (var i = 0; i < error.length; i++) {
                        self.noticeListener.splice(error[i], 1);
                    }
                } else if (message.type === "LETTER") {
                    var letter = message.message;
                    var error = [];
                    for (var i = 0; i < self.letterListener.length; i++) {
                        try {
                            self.letterListener[i](letter);
                        } catch (e) {
                            console.warn(e);
                            error.push(i);
                        }
                    }
                    for (var i = 0; i < error.length; i++) {
                        self.letterListener.splice(error[i], 1);
                    }
                } else if (message.type === "CHAT") {
                    var chat = message.message;
                    var error = [];
                    for (var i = 0; i < self.chatListener.length; i++) {
                        try {
                            self.chatListener[i](chat);
                        } catch (e) {
                            console.warn(e);
                            error.push(i);
                        }
                    }
                    for (var i = 0; i < error.length; i++) {
                        self.chatListener.splice(error[i], 1);
                    }
                } else if (message.type === "EVENT") {
                    var event = message.message;
                    var error = [];
                    for (var i = 0; i < self.eventListener.length; i++) {
                        try {
                            self.eventListener[i](event);
                        } catch (e) {
                            console.warn(e);
                            error.push(i);
                        }
                    }
                    for (var i = 0; i < error.length; i++) {
                        self.eventListener.splice(error[i], 1);
                    }
                } else if (message.type === "TASK") {
                    var task = message.message;
                    var error = [];
                    for (var i = 0; i < self.taskListener.length; i++) {
                        try {
                            self.taskListener[i](task);
                        } catch (e) {
                            console.warn(e);
                            error.push(i);
                        }
                    }
                    for (var i = 0; i < error.length; i++) {
                        self.taskListener.splice(error[i], 1);
                    }
                }
            }
        };
        this.websocket.onclose = function (ev) {
            toastr.warning("您的WebSocket连接已断开，导致无法及时接受服务器消息，请刷新页面");
        };
        this.websocket.onerror = function (ev) {
            toastr.warning("您的WebSocket连接出现错误，导致无法及时接受服务器消息，请联系系统管理员");
        };
    };
    // 发送WebSocket消息到服务端
    this.send = function (message) {
        if (this.validate() === false) {
            this.connect();
        }
        var websocket = this.websocket;
        var interval = setInterval(function () {
            if (websocket.readyState === WebSocket.CONNECTING) return;
            websocket.send(message);
            clearInterval(interval);
        }, 1000);

    };
    // 断开WebSocket连接
    this.disconnect = function () {
        this.websocket.close();
    };
    // 发送WebSocket心跳
    this.heartbeat = function () {
        var heartbeat = {type: "EVENT", message: {type: "HEARTBEAT", date: new Date().format("yyyy-MM-dd HH:mm:ss")}};
        this.send(JSON.stringify(heartbeat));
    };
    // 删除被关闭的iFrame注册的事件
    this.unregister = function(url) {
        var index = [];
        for (var i = 0; i < this.noticeListener.length; i++) {
            if (this.noticeListener[i].owner && this.noticeListener[i].owner.includes(url)) {
                index.push(i);
            }
        }
        for (var i = 0; i < index.length; i++) {
            this.noticeListener.splice(index[i], 1);
        }

        var index = [];
        for (var i = 0; i < this.letterListener.length; i++) {
            if (this.letterListener[i].owner && this.letterListener[i].owner.includes(url)) {
                index.push(i);
            }
        }
        for (var i = 0; i < index.length; i++) {
            this.letterListener.splice(index[i], 1);
        }

        var index = [];
        for (var i = 0; i < this.chatListener.length; i++) {
            if (this.chatListener[i].owner && this.chatListener[i].owner.includes(url)) {
                index.push(i);
            }
        }
        for (var i = 0; i < index.length; i++) {
            this.chatListener.splice(index[i], 1);
        }

        var index = [];
        for (var i = 0; i < this.eventListener.length; i++) {
            if (this.eventListener[i].owner && this.eventListener[i].owner.includes(url)) {
                index.push(i);
            }
        }
        for (var i = 0; i < index.length; i++) {
            this.eventListener.splice(index[i], 1);
        }

        var index = [];
        for (var i = 0; i < this.taskListener.length; i++) {
            if (this.taskListener[i].owner && this.taskListener[i].owner.includes(url)) {
                index.push(i);
            }
        }
        for (var i = 0; i < index.length; i++) {
            this.taskListener.splice(index[i], 1);
        }
    }
}
// 即时通讯
function ChatCtrl() {
    // 右上角消息下拉框显示的未读消息条数
    this.top = 5;
    // 容纳未读消息数量的dom
    this.countId = "#chat-count";
    // 容纳未读消息内容的dom
    this.containerId = "#chat-container";
    // 未读消息的html模板
    this.template = "";
    // 当前用户所有消息
    this.chats = [];
    // 获取未读消息的html模板
    this.getTemplate = function () {
        this.template = $(this.containerId).prop("innerHTML");
        $(this.containerId).html("");
    };
    // 到本地存储中获取消息记录
    this.getChats = function () {
        var value = localStorage.getItem("chat");
        if (Utils.notEmpty(value)) {
            this.chats = JSON.parse(value);
        }
    };
    // 将未读消息情况绘制到页面
    this.setChats = function (userId, users) {
        if (userId === undefined || users === undefined || users.length === 0) {
            return;
        }
        var unreadChats = [];
        for (var i = 0; i < this.chats.length; i++) {
            var chat = this.chats[i];
            if (chat.to === userId && chat.read === false) {
                unreadChats.push(chat);
            }
        }
        $(this.countId).html(unreadChats.length);
        $(this.containerId).html("");
        for (var i = 1; i <= this.top; i++) {
            var unreadChat = unreadChats[unreadChats.length - i];
            if (!unreadChat) {
                continue;
            }
            var user = undefined;
            for (var j = 0; j < users.length; j++) {
                if (users[j].id === unreadChat.from) {
                    user = users[j];
                    break;
                }
            }
            var html = this.template
                .replace(new RegExp("{{userId}}", "gm"), unreadChat.from)
                .replace(new RegExp("{{name}}", "gm"), user ? user.userName : "用户不存在")
                .replace(new RegExp("{{message}}", "gm"), unreadChat.message)
                .replace(new RegExp("{{time}}", "gm"), unreadChat.time)
                .replace(new RegExp("{{image}}", "gm"), Utils.getHeadImageForFrame(user.image));
            $(this.containerId).append(html);
        }
    };
    // 将消息记录保存到本地存储
    this.saveChats = function () {
        localStorage.setItem("chat", JSON.stringify(chats));
    };
    // 添加一个消息
    this.addChat = function (from, to, message, read) {
        var chat = {};
        chat.from = from;
        chat.to = to;
        chat.message = message;
        chat.read = read;
        chat.time = new Date().format("yyyy-MM-dd HH:mm:ss");
        this.chats.push(chat);
    };
    // 将消息设为已读
    this.readChats = function (from, to) {
        for (var i = 0; i < this.chats.length; i++) {
            var chat = this.chats[i];
            if (chat.from === from && chat.to === to) {
                chat.read = true;
            }
        }
    };
    // 查询两个用户之间的消息
    this.searchChats = function (userId1, userId2) {
        var result = [];
        for (var i = 0; i < this.chats.length; i++) {
            if ((this.chats[i].from === userId1 && this.chats[i].to === userId2) ||
                (this.chats[i].from === userId2 && this.chats[i].to === userId1)) {
                result.push(this.chats[i]);
            }
        }
        return result;
    };
    // 统计from用户发给to用户，但是to用户尚未阅读的消息
    this.countUnread = function (from, to) {
        var count = 0;
        for (var i = 0; i < this.chats.length; i++) {
            if (this.chats[i].from === from &&
                this.chats[i].to === to &&
                this.chats[i].read === false) {
                count = count + 1;
            }
        }
        return count;
    }
}
// 站内信
function LetterCtrl() {
    // 右上角下拉框显示的未读站内信条数
    this.top = 5;
    // 容纳未读站内信数量的dom
    this.countId = "#letter-count";
    // 容纳未读站内信内容的dom
    this.containerId = "#letter-container";
    // 未读站内信的模板
    this.template = "";
    // 未读站内信总数量
    this.total = 0;
    // 未读站内信
    this.letters = [];
    // 获得到所有未读站内信监听器
    this.letterListener = [];
    // 获取未读站内信的模板
    this.getTemplate = function () {
        this.template = $(this.containerId).prop("innerHTML");
        $(this.containerId).html("");
    };
    // 查询未读站内信
    this.getLetters = function () {
        var self = this;
        $.ajax({
            url: Url.baseService.letterPageByKeyword + "?readed=false",
            type: HttpMethod.get,
            headers: {pageSize: self.top, pageNumber: 1},
            success: function (result, status, xhr) {
                self.total = result.total;
                self.letters = result.records;
                var error = [];
                for (var i = 0; i < self.letterListener.length; i++) {
                    try {
                        self.letterListener[i](self.letters);
                    } catch (e) {
                        console.warn(e);
                        error.push(i);
                    }
                }
                for (var i = 0; i < error.length; i++) {
                    self.letterListener.splice(error[i], 1);
                }
            }
        });
    };
    // 将未读站内信绘制到页面
    this.setLetter = function () {
        $(this.countId).html(this.total);
        $(this.containerId).html("");
        for (var i = 0; i < this.letters.length; i++) {
            var letter = this.letters[i];
            var classfa = "fa-envelope";
            var classtext = "";
            if (letter.type === "ERROR") {
                classfa = "fa-bug";
                classtext = "text-danger";
            } else if (letter.type === "WARN") {
                classfa = "fa-exclamation-triangle";
                classtext = "text-warning";
            } else if (letter.type === "SUCCESS") {
                classfa = "fa-check-square";
                classtext = "text-success";
            } else if (letter.type === "INFO") {
                classfa = "fa-bell";
                classtext = "text-info";
            }
            var html = this.template
                .replace(new RegExp("{{id}}", "gm"), letter.id)
                .replace(new RegExp("{{message}}", "gm"), letter.message)
                .replace(new RegExp("{{title}}", "gm"), letter.message.length <= 10 ? letter.message : (letter.message.substr(1, 9) + "..."))
                .replace(new RegExp("{{date}}", "gm"), letter.createDate)
                .replace(new RegExp("{{classfa}}", "gm"), classfa)
                .replace(new RegExp("{{classtext}}", "gm"), classtext);
            $(this.containerId).append(html);
        }
    };
}
// 任务
function TaskCtrl() {
    // 右上角下拉框显示的任务条数
    this.top = 5;
    // 任务下拉按钮的dom
    this.show1Id = "#task-show-1";
    this.show2Id = "#task-show-2";
    // 容纳任务数量的dom
    this.countId = "#task-count";
    // 容纳任务内容的dom
    this.containerId = "#task-container";
    // 任务的模板
    this.template = "";
    // 任务总数量
    this.total = 0;
    // 任务
    this.tasks = [];
    // 获得到所有任务监听器
    this.taskListener = [];
    // 任务进度刷新定时任务
    this.taskRefresher = undefined;
    // 获取任务的模板
    this.getTemplate = function () {
        this.template = $(this.containerId).prop("innerHTML");
        $(this.containerId).html("");
    };
    // 查询任务
    this.getTasks = function () {
        var self = this;
        $.ajax({
            url: Url.baseService.taskPageByKeyword,
            type: HttpMethod.get,
            headers: {pageSize: self.top, pageNumber: 1},
            success: function (result, status, xhr) {
                self.total = result.running + result.pending;
                self.tasks = result.records;
                var error = [];
                for (var i = 0; i < self.taskListener.length; i++) {
                    try {
                        self.taskListener[i](self.tasks);
                    } catch (e) {
                        console.warn(e);
                        error.push(i);
                    }
                }
                for (var i = 0; i < error.length; i++) {
                    self.taskListener.splice(error[i], 1);
                }
            }
        });
    };
    // 将任务绘制到页面
    this.setTasks = function () {
        $(this.countId).html(this.total);
        $(this.containerId).html("");
        for (var i = 0; i < this.tasks.length; i++) {
            var task = this.tasks[i];

            var classfa = "fa-envelope";
            var classtext = "";
            var classbg = "";
            var striped = "";
            var running = "";
            var width = "0";
            if (task.status === "ERROR") {
                classfa = "fa-bug";
                classtext = "text-danger";
                classbg = "bg-danger";
                width = "100";
            } else if (task.status === "PENDING") {
                classfa = "fa-exclamation-triangle";
                classtext = "text-warning";
                classbg = "bg-warning";
                striped = "progress-bar-striped";
                running = "running";
                width = "0";
            } else if (task.status === "SUCCESS") {
                classfa = "fa-pinner fa-check-square";
                classtext = "text-success";
                classbg = "bg-success";
                width = "100";
            } else if (task.status === "RUNNING") {
                classfa = "fa-spinner fa-spin";
                classtext = "text-info";
                classbg = "bg-info";
                striped = "progress-bar-striped";
                running = "running";
                width = "0";
            }

            var html = this.template
                .replace(new RegExp("{{id}}", "gm"), task.id)
                .replace(new RegExp("{{name}}", "gm"), task.name)
                .replace(new RegExp("{{title}}", "gm"), task.name.length <= 10 ? task.name : (task.name.substr(0, 9) + "..."))
                .replace(new RegExp("{{status}}", "gm"), task.status)
                .replace(new RegExp("{{startDate}}", "gm"), task.startDate ? task.startDate : "-")
                .replace(new RegExp("{{finishDate}}", "gm"), task.startDate ? task.startDate : "-")
                .replace(new RegExp("{{classfa}}", "gm"), classfa)
                .replace(new RegExp("{{classtext}}", "gm"), classtext)
                .replace(new RegExp("{{classbg}}", "gm"), classbg)
                .replace(new RegExp("{{striped}}", "gm"), striped)
                .replace(new RegExp("{{running}}", "gm"), running)
                .replace(new RegExp("{{evaluate}}", "gm"), task.evaluate)
                .replace(new RegExp("{{width}}", "gm"), width)
            $(this.containerId).append(html);
        }
        if (this.total > 0) {
            if (!$(this.show1Id).hasClass("show")) {
                $(this.show1Id).addClass("show");
            }
            if (!$(this.show2Id).hasClass("show")) {
                $(this.show2Id).addClass("show");
            }
            this.setRunningWidth();
            this.startRunningRefresh();
        } else {
            if ($(this.show1Id).hasClass("show")) {
                $(this.show1Id).removeClass("show");
            }
            if ($(this.show2Id).hasClass("show")) {
                $(this.show2Id).removeClass("show");
            }
            this.stopRunningRefresh();
        }
    };
    // 启动更新任务进度定时器
    this.startRunningRefresh = function () {
        var self = this;
        this.taskRefresher = setInterval(function () {
            self.setRunningWidth();
        }, 1000);
    };
    this.stopRunningRefresh = function () {
        clearInterval(this.taskRefresher);
    };
    // 更新任务进度
    this.setRunningWidth = function () {
        $(this.containerId).find(".progress-task").each(function (i, n) {
            var evaluate = $(n).attr("data-evaluate");
            var start = $(n).attr("data-start-date");
            var status = $(n).attr("data-status");
            if (status === "RUNNING") {
                var startDate = new Date(start);
                var nowDate = new Date();
                var cost = nowDate.getTime() - startDate.getTime();
                var width = cost / evaluate * 100;
                if (width > 99) {
                    width = 99;
                }
                $(n).css("width", width + "%");
            }
        })
    };
}
// 窗口
function WindowCtrl() {
    // 事件监听
    this.tabChangeListers = [];
    // 初始化
    this.init = function () {
        var self = this;
        $('.content-wrapper').IFrame({
            onTabChanged: function onTabChanged(item) {
                var href = $(item).attr("href");
                var src = $(href).find("iframe").attr("src");

                var error = [];
                for (var i = 0; i < self.tabChangeListers.length; i++) {
                    if (self.tabChangeListers[i].owner === undefined || self.tabChangeListers[i].owner.includes(src)) {
                        try {
                            self.tabChangeListers[i]();
                        } catch (e) {
                            console.warn(e);
                            error.push(i);
                        }
                    }
                }
                for (var i = 0; i < error.length; i++) {
                    self.tabChangeListers.splice(error[i], 1);
                }
                return item;
            }
        });
    }
    // 打开窗口
    this.open = function (id, title, link) {
        $('.content-wrapper').IFrame('createTab', title, link, id, true);
    };
    // 切换窗口
    this.switch = function (id) {
        $('.content-wrapper').IFrame('switchTab', id);
    };
    // 关闭窗口
    this.close = function () {
        $('.content-wrapper').IFrame('removeActiveTab');
    }
    // 打开菜单
    this.menu = function (href) {
        $("nav.mt-2 > ul > li > a[href*='" + href + "']").click();
    }
    // 删除被关闭的iFrame注册的事件
    this.unregister = function(url) {
        var index = [];
        for (var i = 0; i < this.tabChangeListers.length; i++) {
            if (this.tabChangeListers[i].owner && this.tabChangeListers[i].owner.includes(url)) {
                index.push(i);
            }
        }
        for (var i = 0; i < index.length; i++) {
            this.tabChangeListers.splice(index[i], 1);
        }
    }
}
// 菜单
function ServiceCtrl() {
    this.hideByService = function () {
        $.ajax({
            url: Url.serviceList,
            type: HttpMethod.get,
            success: function (result, status, xhr) {
                var $binds = $("[data-bind-service]");
                var $first = undefined;
                $binds.each(function (i, n) {
                    var $bind = $(n);
                    var bindService = $bind.attr("data-bind-service");
                    var serviceExists = false;
                    for (var i = 0; i < result.length; i++) {
                        if (result[i].name === bindService && result[i].upCount > 0) {
                            if ($first === undefined && $bind.find("[menu-link]").length > 0) {
                                $first = $bind;
                            }
                            serviceExists = true;
                            break;
                        }
                    }
                    if (serviceExists)  {
                        $bind.removeClass("hide-importment");
                    }
                });
                var menuLink = $first.find("[menu-link]").attr("menu-link");
                $("[menu-content][menu-content=" + menuLink + "]").removeClass("hide");
                $("[menu-content][menu-content!=" + menuLink + "]").addClass("hide");
            }
        });
    }
}
// 下拉
function TitleSelectCtrl() {
    // 事件监听
    this.listeners = [];
    this.init = function () {
        var self = this;
        $("#title-select").change(function () {
            var value = $("#title-select").val();
            var src = $(".tab-pane.active.show>iframe").attr("src");
            var error = [];
            for (var i = 0; i < self.listeners.length; i++) {
                if (self.listeners[i].owner === undefined || self.listeners[i].owner.includes(src)) {
                    try {
                        self.listeners[i](value);
                    } catch (e) {
                        console.warn(e);
                        error.push(i);
                    }
                }
            }
            for (var i = 0; i < error.length; i++) {
                self.listeners.splice(error[i], 1);
            }
        });
    }
    this.hide = function () {
        $("#title-select").hide();
    }
    this.loadByUrl = function (url, key, value, def) {
        var self = this;
        $.ajax({
            url: url,
            type: HttpMethod.get,
            headers: {pageSize: MaxPageSize, pageNumber: 1},
            success: function (result, status, xhr) {
                self.loadByData(result.records, key, value, def);
            }
        })
    }
    this.loadByData = function (data, key, value, def) {
        var html = "";
        for (var i = 0; i < data.length; i++) {
            html += "<option value='" + data[i][key] + "'>" + data[i][value] + "</option>"
        }
        $("#title-select").html(html);
        if (def) {
            $("#title-select").val(def).trigger("change");
        } else {
            $("#title-select").trigger("change");
        }
    }
    this.load = function (urlOrData, key, value, def) {
        $("#title-select").show();
        if (typeof (urlOrData) === "string") {
            this.loadByUrl(urlOrData, key, value, def);
        } else {
            this.loadByData(urlOrData, key, value, def);
        }
    }
    this.unregister = function(url) {
        var index = [];
        for (var i = 0; i < this.listeners.length; i++) {
            if (this.listeners[i].owner && this.listeners[i].owner.includes(url)) {
                index.push(i);
            }
        }
        for (var i = 0; i < index.length; i++) {
            this.listeners.splice(index[i], 1);
        }
    }
}
// 外层框架
function FrameCtrl() {
    this.toastr = toastr;
    this.waitingCtrl = new WaitingCtrl();
    this.confirmCtrl = new ConfirmCtrl();
    this.authCtrl = new AuthCtrl();
    this.userCtrl = new UserCtrl();
    this.websockerCtrl = new WebsocketCtrl();
    this.chatCtrl = new ChatCtrl();
    this.letterCtrl = new LetterCtrl();
    this.taskCtrl = new TaskCtrl();
    this.windowCtrl = new WindowCtrl();
    this.serviceCtrl = new ServiceCtrl();
    this.titleSelectCtrl = new TitleSelectCtrl();
    // 心跳，定时发动rest心跳和websocket心跳
    this.heartBeat = function () {
        var self = this;
        setInterval(function () {
            self.authCtrl.heartbeat();
            self.websockerCtrl.heartbeat();
        }, 10 * 60 * 1000);
    };
    // 绑定事件
    this.bind = function () {
        var self = this;
        // 菜单
        $("[menu-link]").click(function () {
            var menu = $(this).attr("menu-link");
            $("[menu-content][menu-content=" + menu + "]").removeClass("hide");
            $("[menu-content][menu-content!=" + menu + "]").addClass("hide");
        });
        // 绑定查看全部站内信事件
        $("#letter").click(function () {
            $("nav.mt-2 a[href*='letter.html']").click();
        });
        // 绑定查看全部任务事件
        $("#task").click(function () {
            $("nav.mt-2 a[href*='task.html']").click();
        });
        $("#task-container").on("click", ".task-item", function () {
            var id = $(this).attr("data-id");
            var uuid = Math.random().toString(36).slice(-8);
            var name = "异步任务详情";
            var url = "cloud/html/task-detail.html?id=" + id;
            self.windowCtrl.open(uuid, name, url);
        });
        // 登出页面
        $("#logout").click(function () {
            self.authCtrl.logout();
        });
        // 关闭
        $("a[data-widget='iframe-close']").click(function () {
            var src = $(".tab-pane.active.show>iframe").attr("src");
            self.websockerCtrl.unregister(src);
            self.windowCtrl.unregister(src);
            self.titleSelectCtrl.unregister(src);

        })
        // 仪表盘
        $("#logo").click(function () {
            self.windowCtrl.open("dashboard", "仪表盘","cloud/html/dashboard.html");
        })
    };
    // 初始化
    this.init = function () {
        var self = this;
        this.windowCtrl.init();
        this.titleSelectCtrl.init();
        // 注册事件
        this.authCtrl.sessionListener.push(function (session) {
            // 获取session后绘制用户信息到html
            self.authCtrl.setSession();
        });
        this.authCtrl.sessionListener.push(function (session) {
            // 获取session后连接websocket
            self.websockerCtrl.connect(session.id);
        });
        this.authCtrl.sessionListener.push(function (session) {
            // 获取session后绘制当前用户的未读消息到html
            self.chatCtrl.setChats(session.id, self.userCtrl.users);
        });
        this.userCtrl.userListener.push(function (users) {
            // 获取系统所有用户后补充即时消息下拉框内的用户信息
            self.chatCtrl.setChats(self.authCtrl.session, users);
        });
        this.letterCtrl.letterListener.push(function (letters) {
            // 获取未读站内信后将未读站内信绘制到html
            self.letterCtrl.setLetter();
        });
        this.taskCtrl.taskListener.push(function (tasks) {
            // 获取任务后将任务绘制到html
            self.taskCtrl.setTasks();
        });
        this.websockerCtrl.noticeListener.push(function (notice) {
            // 收到通知消息后通过toastr显示到页面
            if (notice.type === "SUCCESS") {
                toastr.success(notice.message);
            } else if (notice.type === "ERROR") {
                toastr.error(notice.message);
            } else if (notice.type === "WARN") {
                toastr.warning(notice.message);
            } else if (notice.type === "INFO") {
                toastr.info(notice.message);
            } else {
                toastr.info(notice.message);
            }
        });
        this.websockerCtrl.letterListener.push(function (letter) {
            // 收到站内信消息后重新获取未读站内信信息，并绘制到页面
            self.letterCtrl.getLetters();
        });
        this.websockerCtrl.taskListener.push(function (task) {
            if (task.type !== "LOG") {
                // 收到任务后重新获取任务信息，并绘制到页面
                self.taskCtrl.getTasks();
            }
        });
        this.websockerCtrl.chatListener.push(function (chat) {
            // 消息即时通讯消息后将消息内容添加到聊天记录
            self.chatCtrl.addChat(chat.userId, self.authCtrl.session.id, chat.message, false);
            // 将未读消息绘制到html
            if (self.authCtrl.session) {
                self.chatCtrl.setChats(self.authCtrl.session.id, self.userCtrl.users);
            }
        });
        this.websockerCtrl.eventListener.push(function (event) {
            if (event.type === "ONLINE") {
                self.userCtrl.userOnline(event.data);
            } else if (event.type === "OFFLINE") {
                self.userCtrl.userOffline(event.data);
            }
        });
        this.windowCtrl.tabChangeListers.push(function () {
            self.titleSelectCtrl.hide();
        })
        // 获取模板
        this.chatCtrl.getTemplate();
        this.letterCtrl.getTemplate();
        this.taskCtrl.getTemplate();
        // 获取数据
        this.authCtrl.getSession();
        this.userCtrl.getUsers();
        this.chatCtrl.getChats();
        this.letterCtrl.getLetters();
        this.taskCtrl.getTasks();
        // 隐藏菜单
        this.serviceCtrl.hideByService();
    };
}

var frameCtrl = new FrameCtrl();
frameCtrl.bind();
frameCtrl.init();
frameCtrl.heartBeat();
frameCtrl.windowCtrl.open("dashboard", "仪表盘","cloud/html/dashboard.html");

